package it.afs.wicket;

import it.afs.wicket.DictionaryItem;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;

public class DictionaryDropDownChoice extends DropDownChoice<String>
{
	private static final long serialVersionUID = 5326462329920627647L;
	
	//private IModel<List<DictionaryItem>> choices;
	private DictionaryHashChoiceModel hashChoices;
	
	public DictionaryDropDownChoice(String id)
	{
		super(id);
		
	}

	public DictionaryDropDownChoice(String id, IModel<String> model, IModel<List<DictionaryItem>> choices)
	{
		super(id);
		
		hashChoices = new DictionaryHashChoiceModel(choices);
		
		setModel(model);
		setChoices(new DictionaryChoiceModel(choices));
		setChoiceRenderer(new DictionaryChoiceRenderer());
		
	}
	
	@Override
	protected void onDetach()
	{
		hashChoices.detach();
		super.onDetach();
	}
	
	private class DictionaryChoiceRenderer implements IChoiceRenderer<String>
	{
		private static final long serialVersionUID = 6799447945703835320L;

		@Override
		public Object getDisplayValue(String object)
		{
			return hashChoices.getObject().get(object);
		}

		@Override
		public String getIdValue(String object, int index) {
			return String.valueOf(index);
		}
	}
	
	private class DictionaryChoiceModel extends LoadableDetachableModel<List<String>>
	{
		private static final long serialVersionUID = 5029245996452445965L;
		
		private IModel<List<DictionaryItem>> choices;
		
		public DictionaryChoiceModel(IModel<List<DictionaryItem>> choices)
		{
			this.choices = choices;
		}
		
		@Override
		protected List<String> load()
		{
			ArrayList<String> stringChoices = new ArrayList<String>(choices.getObject().size());
			for(DictionaryItem item : choices.getObject())
			{
				stringChoices.add(item.getValue());
			}
			return stringChoices;
		}
	}
	
	private class DictionaryHashChoiceModel extends LoadableDetachableModel<Hashtable<String, String>>
	{
		private static final long serialVersionUID = -8553254639928972498L;
		
		private IModel<List<DictionaryItem>> choices;
		
		public DictionaryHashChoiceModel(IModel<List<DictionaryItem>> choices)
		{
			this.choices = choices;
		}
		
		@Override
		protected Hashtable<String, String> load()
		{
			Hashtable<String, String> hashChoices = new Hashtable<String, String>();
			for(DictionaryItem item : choices.getObject())
			{
				hashChoices.put(item.getValue(), item.toChoiceString());
			}
			return hashChoices;
		}
	}
}
